Thumb

What is late binding and early binding?

1/12/2020 7:12:47 AM

Early binding can flag errors at compile time. With late binding there is a risk of run time exceptions. Early binding is much better for performance and should always be preferred over late binding. Use late binding only when working with an object’s that are not available at compile time. Now given bellow the example the code and explain the code:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Reflection;
using testForClass1;
namespace testFor
{
    public class Program
    {
        static void Main(string[] args)
        {
            //early binding
            Student student = new Student();
            string earlyName = student.GetFullName("Farhan", "Sakib");
            Console.WriteLine("early binding : " + earlyName);

            //late binding
            Assembly excutingAssembly = Assembly.GetExecutingAssembly();
            Type studentType = excutingAssembly.GetType("testFor.Student");
            object studentInstance = Activator.CreateInstance(studentType);
            MethodInfo getFullNameMethod = studentType.GetMethod("GetFullName");
            string[] parameters = new string[2];
            parameters[0] = "Farhan";
            parameters[1] = "Sakib";
            string lateName = (string)getFullNameMethod.Invoke(studentInstance, parameters);
            Console.WriteLine("late binding : " + lateName);

            Console.Read();
        }
    }
    public class Student
    {
        public string GetFullName(string firstName, string lastName)
        {
            return firstName + " " + lastName;
        }
    }
}

Early binding is show in compile time error and late binding show error in run time exceptions.